<?php

App::uses('AppModel', 'Model');
App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationGroupType Model
 *
 * @property Organisation $Organisation
 * @property OrganisationGroup $OrganisationGroup
 */
class OrganisationGroupType extends CompositeKeyModel {

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * hasMany associations
     *
     * @var array
     */
    public $hasMany = array(
        'OrganisationGroup' => array(
            'className' => 'OrganisationGroup',
            'foreignKey' => 'organisation_group_type_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    public function group_stats($organisation_id) {
        
        $response = $this->find('all', array(
            'contain' => array(
                'OrganisationGroup' => array(
                    'fields' => array('id', 'name', 'organisation_member_group_count'),
                    'conditions' => array(
                        'OrganisationGroup.active' => 1,
                        'OrganisationGroup.organisation_id' => $organisation_id
                    )
                )
            ),
            'conditions' => array(
                'OrganisationGroupType.organisation_id' => $organisation_id,
                'OrganisationGroupType.active' => 1
            )
        ));
        
        $stats = array();
        
        foreach($response as $gtype) {
            $name = $gtype['OrganisationGroupType']['name'];
            $stats[$name] = array();
            
            foreach($gtype['OrganisationGroup'] as $group) {
                $stats[$name][$group['name']] = $group['organisation_member_group_count'];
            }
        }
        
        return $stats;
    }
}
